<script setup>
import { ref } from 'vue'
import { classesAllService } from '@/api/classes.js'
import { studentAddressService } from '@/api/statistic.js';
import * as echarts from 'echarts'

const chert = ref()

const classId = ref()

const classes = ref()

const className = ref('所有学生')

const chartData = ref()

const getAllClasses = async () => {
    try {
        let result = await classesAllService();
        classes.value = result.data;
    } catch (error) {
        console.log('Error fetching data:', error);
    }
}

getAllClasses();

const getStudentAddress = async (classId) => {
    if(classId == undefined){
        classId = '';
    }

    try {
        let result = await studentAddressService(classId);
        chartData.value = result.data;
    } catch (error) {
        console.log('Error fetching data:', error)
    }

    for (let i = 0; i < classes.value.length; i++) {
        if (classId === classes.value[i].id) {
            className.value = classes.value[i].name
        }
    }

    const X_datas = []

    for (let i = 0; i < chartData.value.length; i++) {
        X_datas.push(chartData.value[i].name)
    }

    const Y_datas = []

    for (let i = 0; i < chartData.value.length; i++) {
        Y_datas.push(chartData.value[i].value)
    }

    var chart = echarts.init(chert.value)

    var option = (option = {
        title: {
            text: '[' + className.value + ']的学生家庭住址统计',
            subtext: 'Fake Data',
            left: 'center'
        },
        xAxis: {
            type: 'category',
            data: X_datas
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: Y_datas,
                type: 'bar'
            }
        ]
    })

    chart.setOption(option);
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>学生家庭住址统计</span>
            </div>
        </template>

        <el-form inline>
            <el-form-item label="班级名称：" prop="classId">
                <el-select v-model="classId" placeholder="请选择课程">
                    <el-option v-for="c in classes" :key="c.id" :label="c.name" :value="c.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="getStudentAddress(classId); classId = '';className='所有学生'">搜索</el-button>
                <el-button @click="classId = ''; chartData = []">重置</el-button>
            </el-form-item>
        </el-form>

        <div ref="chert" class="chert" id="chert">
        </div>
    </el-card>
</template>

<style>
.page-container {
    width: 100%;
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .chert {
        width: 700px;
        height: 400px;
    }
}
</style>